import type { Module } from 'vuex';
import { getTest, getUserById, getUserMenus } from '@/api/request';
import LocalCache from '@/utils/cache';
import router from '@/router';
interface ILoginState {
  token: string;
  userInfo: any;
  userMenus: any;
  permissions: string[];
}
interface IRootState {
  name: string;
  entireRoles: any[];
  entireDepartments: any[];
  entireMenus: any[];
}

const login: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: {},
      permissions: []
    };
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token;
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    saveUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;
    }
  },
  actions: {
    async accountLoginAction({ commit }, account: any) {
      // 1.用户登录
      const loginResult: any = await getTest(account);
      const { id, token } = loginResult;
      commit('saveToken', token);
      LocalCache.setCache('token', token);

      // 2.获取用户信息
      const userInfo: any = await getUserById(id);
      commit('saveUserInfo', userInfo);
      LocalCache.setCache('userInfo', userInfo);

      // 3.用户菜单树
      const userMenus: any = await getUserMenus(userInfo.role.id);
      commit('saveUserMenus', userMenus);
      LocalCache.setCache('userMenus', userMenus);

      router.push('/main');
    },

    loadLocalCache({ commit, dispatch }) {
      const token = LocalCache.getCache('token');
      if (token) {
        commit('saveToken', token);
        // dispatch('getInitalDataAction', null, { root: true });
      }
      const userInfo = LocalCache.getCache('userInfo');
      if (userInfo) {
        commit('saveUserInfo', userInfo);
      }
      const userMenus = LocalCache.getCache('userMenus');
      if (userMenus) {
        commit('saveUserMenus', userMenus);
      }
    }
  },
  modules: {}
};

export default login;
